<<<<<<< HEAD
from . import admin_bp 
from flask import request,jsonify
from app.models import ModuleType,OperationType
from app.models import User, UserProfile,OperationLog,Role,LoginLog
=======
from . import admin_bp
from flask import request, jsonify
from app.models import ModuleType, OperationType
from app.models import User, UserProfile, OperationLog, Role
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
from config import Config
from werkzeug.security import generate_password_hash
from app.extensions import db
from app.decorator import permission_required

<<<<<<< HEAD
@admin_bp.route('/admin/user/list',methods=['GET'])
=======

@admin_bp.route('/admin/user/list', methods=['GET'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_USER, OperationType.QUERY)
def user_list():
    page = request.args.get('page', type=int)
    page_size = request.args.get('pageSize', type=int)
    search_key = request.args.get('searchKey', type=str)
    uid = request.args.get('uid', type=int)
<<<<<<< HEAD
    
    # 创建基础查询，加入关联查询
    query = User.query.outerjoin(UserProfile)
    
=======

    # 创建基础查询，加入关联查询
    query = User.query.outerjoin(UserProfile)

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    # 如果有搜索关键词，添加过滤条件
    if search_key:
        try:
            uid_user = User.query.get(uid)
<<<<<<< HEAD
            operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.ADMIN_USER,operation=OperationType.QUERY,detail=f'搜索用户：{search_key}')
=======
            operation_log = OperationLog(user_id=uid, email=uid_user.email, module=ModuleType.ADMIN_USER,
                                         operation=OperationType.QUERY, detail=f'搜索用户：{search_key}')
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
            db.session.add(operation_log)
            db.session.commit()
        except Exception as e:
            print(e)
        query = query.filter(
            db.or_(
                User.email.like(f'%{search_key}%'),
                UserProfile.name.like(f'%{search_key}%')
            )
        )
<<<<<<< HEAD
    
=======

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    # 获取分页对象
    pagination = query.paginate(
        page=page,
        per_page=page_size,
        error_out=False
    )
<<<<<<< HEAD
    
    # 获取当前页的用户列表
    users = [user.to_json() for user in pagination.items]
    
    # 获取总用户数
    total = pagination.total
    
=======

    # 获取当前页的用户列表
    users = [user.to_json() for user in pagination.items]

    # 获取总用户数
    total = pagination.total

>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    data = {
        'total': total,
        'users': users
    }
<<<<<<< HEAD
    
    return jsonify({'message':'获取用户列表成功','errcode':'0','data':data}),200


@admin_bp.route('/admin/user/add',methods=['POST'])
=======

    return jsonify({'message': '获取用户列表成功', 'errcode': '0', 'data': data}), 200


@admin_bp.route('/admin/user/add', methods=['POST'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_USER, OperationType.ADD)
def user_add():
    email = request.json.get('email')
    role_code = request.json.get('role')
    uid = request.json.get('uid')
<<<<<<< HEAD
    
    role = Role.query.filter_by(code=role_code).first()
        
    password = generate_password_hash(Config.INIT_PASSWORD)
    user = User(email=email,password=password,is_active=True,role_id=role.id)
    uid_user = User.query.get(uid)
    operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.ADMIN_USER,operation=OperationType.ADD,detail=f'添加用户：{email}')
=======

    role = Role.query.filter_by(code=role_code).first()

    password = generate_password_hash(Config.INIT_PASSWORD)
    user = User(email=email, password=password,
                is_active=True, role_id=role.id)
    uid_user = User.query.get(uid)
    operation_log = OperationLog(user_id=uid, email=uid_user.email,
                                 module=ModuleType.ADMIN_USER, operation=OperationType.ADD, detail=f'添加用户：{email}')
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    db.session.add(user)
    db.session.add(operation_log)
    try:
        db.session.commit()
        profile = UserProfile(user_id=user.id)
        db.session.add(profile)
        db.session.commit()
<<<<<<< HEAD
        return jsonify({'message':'添加用户成功','errcode':'0'}),200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message':'添加用户失败','errcode':'-1','error':str(e)}),500
    
    
@admin_bp.route('/admin/user/edit',methods=['PUT'])
=======
        return jsonify({'message': '添加用户成功', 'errcode': '0'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '添加用户失败', 'errcode': '-1', 'error': str(e)}), 500


@admin_bp.route('/admin/user/edit', methods=['PUT'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_USER, OperationType.UPDATE)
def user_edit():
    id = request.json.get('id')
    email = request.json.get('email')
    role = request.json.get('role')
    uid = request.json.get('uid')
    role_record = Role.query.filter_by(code=role).first()
    if not role_record:
        role_record = Role.query.filter_by(name=role).first()

    user = User.query.get(id)
    user.email = email
    user.role_id = role_record.id
    try:
        db.session.commit()
        uid_user = User.query.get(uid)
<<<<<<< HEAD
        operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.ADMIN_USER,operation=OperationType.UPDATE,detail=f'更新用户：{email}')
        db.session.add(operation_log)
        db.session.commit()
        return jsonify({'message':'编辑用户成功','errcode':'0'}),200
=======
        operation_log = OperationLog(user_id=uid, email=uid_user.email, module=ModuleType.ADMIN_USER,
                                     operation=OperationType.UPDATE, detail=f'更新用户：{email}')
        db.session.add(operation_log)
        db.session.commit()
        return jsonify({'message': '编辑用户成功', 'errcode': '0'}), 200
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '编辑用户失败', 'errcode': '-1', 'error': str(e)}), 500


<<<<<<< HEAD
@admin_bp.route('/admin/user/delete',methods=['DELETE'])
=======
@admin_bp.route('/admin/user/delete', methods=['DELETE'])
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
@permission_required(ModuleType.ADMIN_USER, OperationType.DELETE)
def user_delete():
    id = request.json.get('id')
    uid = request.json.get('uid')
    user = User.query.get(id)
    profile = UserProfile.query.filter_by(user_id=id).first()
    uid_user = User.query.get(uid)
<<<<<<< HEAD
    operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.ADMIN_USER,operation=OperationType.DELETE,detail=f'删除用户：{user.email}')
    try:
        db.session.delete(profile)     
=======
    operation_log = OperationLog(user_id=uid, email=uid_user.email, module=ModuleType.ADMIN_USER,
                                 operation=OperationType.DELETE, detail=f'删除用户：{user.email}')
    try:
        db.session.delete(profile)
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
        db.session.delete(user)
        db.session.add(operation_log)
        db.session.commit()
        return jsonify({'message': '删除用户成功', 'errcode': '0'}), 200
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify({'message': '删除用户失败', 'errcode': '-1', 'error': str(e)}), 500


@admin_bp.route('/admin/user/active', methods=['PUT'])
@permission_required(ModuleType.ADMIN_USER, OperationType.UPDATE)
def user_active():
    id = request.json.get('id')
    is_active = request.json.get('is_active')
    uid = request.json.get('uid')
    user = User.query.get(id)
    user.is_active = is_active
    uid_user = User.query.get(uid)
    operation_log = OperationLog(user_id=uid, email=uid_user.email, module=ModuleType.ADMIN_USER,
                                 operation=OperationType.UPDATE, detail=f'修改{user.email}状态')
    db.session.add(operation_log)
    try:
        db.session.commit()
        return jsonify({'message': '修改用户状态成功', 'errcode': '0'}), 200
    except Exception as e:
        print(e)
        db.session.rollback()
<<<<<<< HEAD
        return jsonify({'message':'删除用户失败','errcode':'-1','error':str(e)}),500


@admin_bp.route('/admin/user/active',methods=['PUT'])
@permission_required(ModuleType.ADMIN_USER, OperationType.UPDATE)
def user_active():
    id = request.json.get('id')
    is_active = request.json.get('is_active')
    uid = request.json.get('uid')
    user = User.query.get(id)
    user.is_active = is_active
    uid_user = User.query.get(uid)
    operation_log = OperationLog(user_id=uid,email=uid_user.email,module=ModuleType.ADMIN_USER,operation=OperationType.UPDATE,detail=f'修改{user.email}状态')
    db.session.add(operation_log)
    try:
        db.session.commit()
        return jsonify({'message':'修改用户状态成功','errcode':'0'}),200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message':'修改用户状态失败','errcode':'-1','error':str(e)}),500


=======
        return jsonify({'message': '修改用户状态失败', 'errcode': '-1', 'error': str(e)}), 500
>>>>>>> 7245172afa54706ac2f9973f27248496e8835d1c
